/*//GEN-FIRST:event_jbConcluirActionPerformed
 * To change this template, choose Tools | Templates//GEN-LAST:event_jbConcluirActionPerformed
 * and open the template in the editor.
 */
package Visao.Gerente.Gerenciar;

import Controle.Controlador;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;

/**
 *
 * @author Andre Luiz
 */
public class InserirAlterarSabor extends javax.swing.JFrame {
    ArrayList<ArrayList<String>> categorias;
    GerenciarSabor gerenciar;
    boolean update = false;
    Integer codigoSaborUpdate;
    //Sabor saborUpdadate;
    /**
     * Creates new form InserirAlterarSabor
     */
    public InserirAlterarSabor() {
        initComponents();
        categorias = Controlador.carregarDadosBD_Categorias();
        setarItensCategorias();
        
    }
    
    public InserirAlterarSabor(GerenciarSabor gerenciar) {
        initComponents();
        this.gerenciar = gerenciar;
        categorias = Controlador.carregarDadosBD_Categorias();
        setarItensCategorias();
        
    }
    
    public InserirAlterarSabor(GerenciarSabor gerenciar, int codigo ){
        initComponents();
        this.gerenciar = gerenciar;
        this.update = true;
        this.codigoSaborUpdate = codigo;
        categorias = Controlador.carregarDadosBD_Categorias();
        setarItensCategorias();
        //this.saborUpdadate = Controlador.carregarDadosBD_Sabor(codigo);
        setDadosVisao(Controlador.convertModeloSaborToDadosVisao(codigo));
//        categorias = carregarDadosBD();
//        setarCategorias(categorias);
        
//        jtfSabor.setText(this.saborUpdadate.getNome());
//        int index = getIndexCategoria(this.saborUpdadate.getCategoria().getCodigo())+1;
//        jcbCategoria.setSelectedIndex(index);
//        jtaIngredientes.setText(this.saborUpdadate.getIngredientes());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jtfSabor = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jcbCategoria = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtaIngredientes = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jbConcluir = new javax.swing.JButton();
        jbCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Inserir Sabor");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);

        jLabel1.setText("Sabor:");

        jtfSabor.setPreferredSize(new java.awt.Dimension(170, 20));

        jLabel2.setText("Categoria:");

        jcbCategoria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione uma Categoria" }));
        jcbCategoria.setPreferredSize(new java.awt.Dimension(170, 20));

        jtaIngredientes.setColumns(20);
        jtaIngredientes.setRows(5);
        jScrollPane1.setViewportView(jtaIngredientes);

        jLabel3.setText("Ingredientes");

        jbConcluir.setText("OK");
        jbConcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbConcluirActionPerformed(evt);
            }
        });

        jbCancelar.setText("Cancelar");
        jbCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jbCancelar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbConcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addComponent(jLabel3))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jtfSabor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jcbCategoria, 0, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtfSabor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jcbCategoria, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbConcluir)
                    .addComponent(jbCancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Dimension dialogSize = getSize();
        setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
    }// </editor-fold>                        

    private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        dispose();
    }                                          

    private void jbConcluirActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // Botão Concluir
        if(!update){
            try {
                validarEntradaDados();

                if(Controlador.salvar_Sabor(getDadosVisao())){
                    this.setVisible(false);
                    gerenciar.atualizaTabela();
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e.getMessage(),"Erro!",0);
            }
        }
        else{
            try {
                validarEntradaDados();

                if(Controlador.editar_Sabor(getDadosVisao())){
                    this.setVisible(false);
                    gerenciar.atualizaTabela();
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e.getMessage(),"Erro!",0);
            }
        }
    }                                          

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbCancelar;
    private javax.swing.JButton jbConcluir;
    private javax.swing.JComboBox jcbCategoria;
    private javax.swing.JTextArea jtaIngredientes;
    private javax.swing.JTextField jtfSabor;
    // End of variables declaration                   
    
//    private ArrayList<Categoria> carregarDadosBD(){
//        ArrayList<Categoria> categ = new ArrayList<>();
//        if(Controlador.carregarDadosBD_Categorias(categ)){
//            return categ;
//        }
//        return null;
//    }
//    
    private void setarItensCategorias(){
        for (int i = 0; i < categorias.size(); i++) {
             jcbCategoria.addItem(categorias.get(i).get(1) +" "+ categorias.get(i).get(2));            
        }
    }
    
    private String getCodigoItemCategoriaSelecionada(String itemCategoriaSelecionada){
        for (int i = 0; i < categorias.size(); i++) {
            if(itemCategoriaSelecionada.equalsIgnoreCase( categorias.get(i).get(1) +" "+ categorias.get(i).get(2)))
                return categorias.get(i).get(0);
        }
        
        return null;
    }
    
    private int getIndexItemCategoria(String codigo){
        for (int i = 1; i <= categorias.size(); i++) {
            if(codigo.equalsIgnoreCase( categorias.get(i).get(0)))
                return i;
        }
        return 0;
    }
    
    private void validarEntradaDados() throws Exception {
        //jcbCategoria jtaIngredientes jtfSabor
        Matcher restricao = Pattern.compile("[a-zA-Z]").matcher(jtfSabor.getText());

        if(jtfSabor.getText().length()==0){
            throw new Exception("Digite um mome para o Sabor");
        }
        if(jtfSabor.getText().contains(",")){
            throw new Exception("Nome do Sabor é inválido\nO nome do Sabor não poderá conter virgulas(,)");
        }
        if (!restricao.find()) {
            throw new Exception("Nome do Sabor é inválido!\nO nome deverá conter ao menos uma letra.");
        }
        if(jtaIngredientes.getText()==null || jtaIngredientes.getText().length()==0){
            throw new Exception("Digite os Ingredientes do Sabor!");
        }
        if (jcbCategoria.getSelectedIndex()==0) {
            throw new Exception("Selecione uma Categoria");
        }
    }
    
    private ArrayList<String> getDadosVisao(){
        ArrayList<String> sabor = new ArrayList();
        sabor.add(""+this.codigoSaborUpdate);
        sabor.add(jtfSabor.getText().toUpperCase());
        sabor.add(getCodigoItemCategoriaSelecionada(jcbCategoria.getSelectedItem().toString()));
        sabor.add(jtaIngredientes.getText().toUpperCase());
        
        return sabor;
    }
    
    private void setDadosVisao(ArrayList<String> param){
        System.out.println(param.toString());
        jtfSabor.setText(param.get(1));
        jcbCategoria.setSelectedIndex(getIndexItemCategoria( param.get(3)));
        jtaIngredientes.setText(param.get(2));
    }
    
}
